package com.commonEncryptionAlgorithms.symmetry.RC;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.Security;

public class RC5Example {
    public static void main(String[] args) throws Exception {
        // 添加Bouncy Castle作为安全提供者
        Security.addProvider(new BouncyCastleProvider());

        // 初始化密钥生成器
        KeyGenerator keyGen = KeyGenerator.getInstance("RC5", "BC");
        keyGen.init(128); // 设置密钥长度为128位
        SecretKey secretKey = keyGen.generateKey();

        // 初始化加密器
        Cipher cipher = Cipher.getInstance("RC5/ECB/PKCS7Padding", "BC");

        // 加密
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedData = cipher.doFinal("Hello, World!".getBytes());
        System.out.println("Encrypted Data: " + bytesToHex(encryptedData));

        // 解密
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedData = cipher.doFinal(encryptedData);
        System.out.println("Decrypted Data: " + new String(decryptedData));
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}